/*
 * @FilePath: /flutter_cart/lib/pages/category_page.dart
 * @Author: Yongchao Wang
 * @Date: 2020-03-23 07:41:22
 * @LastEditors: Yongchao Wang
 * @LastEditTime: 2020-12-10 20:54:16
 */

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cart/routers/application.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../service/service_method.dart';
import 'dart:convert';
import '../model/category.dart';
import '../model/category_goods.dart';

import 'package:flutter_screenutil/screenutil.dart';
import 'package:provider/provider.dart';
import '../provide/category.dart';
import '../provide/category_goods_list.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fluro/fluro.dart';

class CategoryPage extends StatefulWidget {
  CategoryPage({Key key}) : super(key: key);

  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('商品分类')),
      body: Container(
        child: Row(
          children: [
            LeftCategoryNav(),
            Column(
              children: [RightCategoryNav(), CategoryGoodsList()],
            )
          ],
        ),
      ),
    );
  }
}

//左侧大类导航
class LeftCategoryNav extends StatefulWidget {
  LeftCategoryNav({Key key}) : super(key: key);

  @override
  _LeftCategoryNavState createState() => _LeftCategoryNavState();
}

class _LeftCategoryNavState extends State<LeftCategoryNav> {
  List<CategoryBigModel> list = [];
  int listIndex = 0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getCategory();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: ScreenUtil().setWidth(180),
      decoration: BoxDecoration(
          border: Border(right: BorderSide(width: 1, color: Colors.black12))),
      child: ListView.builder(
        itemCount: list.length,
        itemBuilder: (context, index) {
          return _leftInkWell(index);
        },
      ),
    );
  }

  void _getCategory() async {
    await getCategory().then((val) {
      var data = jsonDecode(val.toString());
      CategoryBigListModel categoryList =
          CategoryBigListModel.fromJson(data['data']);
      setState(() {
        list = categoryList.data;
      });
      context
          .read<ChildCategory>()
          .getChildCategory(categoryList.data[0].bxMallSubDto);
      context
          .read<CategoryGoodsListProvide>()
          .requestGoodsList(categoryId: categoryList.data[0].mallCategoryId);
    });
  }

  Widget _leftInkWell(index) {
    bool isClick = listIndex == index;
    return InkWell(
      onTap: () {
        setState(() {
          listIndex = index;
        });
        context
            .read<ChildCategory>()
            .getChildCategory(list[index].bxMallSubDto);
        context.read<CategoryGoodsListProvide>().requestGoodsList(
            categoryId: list[index].mallCategoryId, categorySubId: '', page: 1);
        context.read<CategoryGoodsListProvide>().setSelectedIndex(0);
      },
      child: Container(
        height: ScreenUtil().setHeight(100),
        padding: EdgeInsets.only(left: 10, top: 15),
        decoration: BoxDecoration(
            color: isClick ? Color.fromRGBO(236, 236, 236, 1) : Colors.white,
            border:
                Border(bottom: BorderSide(width: 1, color: Colors.black12))),
        child: Text(
          list[index].mallCategroyName,
          style: TextStyle(fontSize: ScreenUtil().setSp(28)),
        ),
      ),
    );
  }
}

class RightCategoryNav extends StatefulWidget {
  RightCategoryNav({Key key}) : super(key: key);

  @override
  _RightCategoryNavState createState() => _RightCategoryNavState();
}

class _RightCategoryNavState extends State<RightCategoryNav> {
  var selectIndex = 0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    List list = context.watch<ChildCategory>().childCategoryList;
    selectIndex = context.watch<CategoryGoodsListProvide>().selectedIndex;
    return Container(
      height: ScreenUtil().setHeight(80),
      width: ScreenUtil().setWidth(570),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(bottom: BorderSide(width: 1, color: Colors.black12))),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, index) {
          return _rightInkWell(list[index], index);
        },
        itemCount: list.length,
      ),
    );
  }

  Widget _rightInkWell(Map item, int index) {
    return InkWell(
      onTap: () {
        context
            .read<CategoryGoodsListProvide>()
            .requestGoodsList(categorySubId: item['mallSubId'], page: 1);
        context.read<CategoryGoodsListProvide>().setSelectedIndex(index);
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
        child: Text(
          item['mallSubName'],
          style: TextStyle(
              fontSize: ScreenUtil().setSp(28),
              color: selectIndex == index ? Colors.pink : Colors.black),
        ),
      ),
    );
  }
}

//商品列表
class CategoryGoodsList extends StatefulWidget {
  CategoryGoodsList({Key key}) : super(key: key);

  @override
  _CategoryGoodsListState createState() => _CategoryGoodsListState();
}

class _CategoryGoodsListState extends State<CategoryGoodsList> {
  List<CategoryGoodsModel> goodsList = [];
  EasyRefreshController _controller = EasyRefreshController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // setState(() {

    // });
  }

  @override
  Widget build(BuildContext context) {
    goodsList = context.watch<CategoryGoodsListProvide>().goodsList;
    if (goodsList.length == 0) {
      return Text('暂无商品');
    } else {
      return Expanded(
          child: Container(
              width: ScreenUtil().setWidth(570),
              child: EasyRefresh(
                controller: _controller,
                header: ClassicalHeader(
                    bgColor: Colors.white,
                    textColor: Colors.pink,
                    infoColor: Colors.pink,
                    showInfo: false,
                    noMoreText: '没有更多',
                    refreshReadyText: '松开手刷新',
                    refreshText: '上拉加载',
                    refreshingText: '加载中',
                    refreshedText: '加载完成'),
                footer: ClassicalFooter(
                    bgColor: Colors.white,
                    textColor: Colors.pink,
                    infoColor: Colors.pink,
                    showInfo: false,
                    noMoreText: '没有更多',
                    loadReadyText: '上拉加载',
                    loadText: '上拉加载',
                    loadingText: '加载中',
                    loadedText: '加载完成'),
                child: ListView.builder(
                  itemCount: goodsList.length,
                  itemBuilder: (context, index) {
                    return _goodsItem(index);
                  },
                ),
                onRefresh: () async {
                  context
                      .read<CategoryGoodsListProvide>()
                      .requestGoodsList(page: 1, controller: _controller);
                },
                onLoad: () async {
                  context
                      .read<CategoryGoodsListProvide>()
                      .requestGoodsList(add: true, controller: _controller);
                },
              )));
    }
  }

  Widget _goodsItem(index) {
    return InkWell(
      onTap: () {
        Application.router.navigateTo(context, "/users/1234",
            transition: TransitionType.fadeIn);
      },
      child: Container(
        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
        decoration: BoxDecoration(
            color: Colors.white,
            border:
                Border(bottom: BorderSide(width: 1, color: Colors.black12))),
        child: Row(
          children: [
            CachedNetworkImage(
              imageUrl: goodsList[index].image,
              width: ScreenUtil().setWidth(200),
            ),
            Column(
              children: [
                Container(
                  padding: EdgeInsets.all(5.0),
                  width: ScreenUtil().setWidth(370),
                  child: Text(
                    goodsList[index].goodsName,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: Colors.black26,
                        fontSize: ScreenUtil().setSp(28)),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 20.0),
                  width: ScreenUtil().setWidth(370),
                  child: Row(children: [
                    Text(
                      '价格：￥' + goodsList[index].presentPrice.toString(),
                      style: TextStyle(
                          color: Colors.pink, fontSize: ScreenUtil().setSp(30)),
                    ),
                    Text(
                      '￥' + goodsList[index].oriPrice.toString(),
                      style: TextStyle(
                          color: Colors.black26,
                          fontSize: ScreenUtil().setSp(24),
                          decoration: TextDecoration.lineThrough),
                    ),
                  ]),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
